package com.homedo.odin.solution.service.bizservice.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.HttpClient;
import com.homedo.odin.solution.enumcode.constant.ConstantUtils;
import com.homedo.odin.solution.model.dto.HebiModel;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author: donglibing
 * @date: 2018/3/26 14:26
 * @Description:
 */
@Service
public class HebiBizService {

    @Value("${Hebi_Host_Url}")
    private String hostUrl;

    @Value("${APPID}")
    private String appId;

    /**
     * 增加河币
     */
    public JSONObject addHebi(MultiValueMap<String, String> params) {
        String url = hostUrl + "/IntegralService/Integral/Add";
        String reslutJson = HttpClient.post(url, params);
        JSONObject jsonObject = JSONObject.fromObject(reslutJson);
        return jsonObject;
    }

    /**
     * 扣减河币
     */
    public JSONObject minusHebi(MultiValueMap<String, String> params) {
        String url = hostUrl + "/IntegralService/Integral/Minus";
        String reslutJson = HttpClient.post(url, params);
        JSONObject jsonObject = JSONObject.fromObject(reslutJson);
        return jsonObject;
    }

    /**
     * 返还河币
     */
    public JSONObject refundHebi(MultiValueMap<String, String> params) {
        String url = hostUrl + "/IntegralService/Integral/Refund";
        String reslutJson = HttpClient.post(url, params);
        JSONObject jsonObject = JSONObject.fromObject(reslutJson);
        return jsonObject;
    }

    /**
     * 获取河币信息
     */
    public HebiModel getHebiinfo(int id) {

        //获取河币
        String url = hostUrl + "/IntegralService/Integral/Info";
        //post请求
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add("AppId", appId);
        params.add("AccountId", String.valueOf(id));
        //发送http请求并返回结果
        String reslutJson = HttpClient.post(url, params);
        JSONObject jsonObject = JSONObject.fromObject(reslutJson);
        Object data = jsonObject.get("data");
        if (!(boolean) jsonObject.get(ConstantUtils.HebiConstants.IS_OK)) {
            throw new BizException(Meta.CODE_500.getCode(), "河币转入到采纳人失败");
        }
        String jsonStr = data.toString();
        HebiModel hebiModel = JSON.parseObject(jsonStr, new TypeReference<HebiModel>() {
        });
        return hebiModel;
    }

}
